﻿using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using vm.Aspects.Security.Cryptography;
using vm.Aspects.Security.Cryptography.Algorithms;

namespace CiphersSamples
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        void EncryptStream(Stream dataStream, Stream encryptedStream)
        {
            using (ICipher cipher = GetCipher())
                cipher.Encrypt(dataStream, encryptedStream);
        }

        void DecryptStream(Stream encryptedStream, Stream dataStream)
        {
            using (ICipher cipher = GetCipher())
                cipher.Decrypt(encryptedStream, dataStream);
        }

        byte[] HashArray(byte[] data)
        {
            using (IHasher hasher = GetHasher())
                return hasher.Hash(data);
        }

        bool VerifyHashArray(byte[] data, byte[] hash)
        {
            using (IHasher hasher = GetHasher())
                return hasher.TryVerifyHash(data, hash);
        }

        byte[] DecryptArray(byte[] encryptedData)
        {
            using (ICipher cipher = GetCipher())
                return cipher.Decrypt(encryptedData);
        }

        byte[] EncryptByteArray(string protectedText)
        {
            using (var cipher = GetCipher())
                return cipher.EncryptText(protectedText);
        }

        byte[] EncryptByteArray(string protectedText)
        {
            using (var cipher = GetCipher())
                return cipher.EncryptText(protectedText);
        }

        ICipher GetCipher()
        {
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            try
            {
                var certs = store.Certificates
                                 .Find(X509FindType.FindByTimeValid, DateTime.Now, false)
                                 .Find(X509FindType.FindBySubjectName, "vm.EncryptionCipherUnitTest", false);
                var cert = certs.Count > 0 ? certs[0] : null;

                Debug.Assert(cert != null);

                return new EncryptedKeyCipher(cert, Symmetric.TripleDes);
            }
            finally
            {
                store.Close();
            }
        }

        private IHasher GetHasher()
        {
            throw new System.NotImplementedException();
        }
    }
}
